package modules

import (
	"config"
	"time"
	"context"
	"log"
	"common"
)

type AuthTask struct {
	loginAuth   *LoginAuth
	refreshTime time.Duration
}

func (a *AuthTask) OnInit() error {
	a.loginAuth = new(LoginAuth)
	config, err := config.ParseConfigFile("/config2.yaml")
	if err != nil {
		return err
	}
	a.loginAuth.InitConfig(config)
	err = a.loginAuth.StartChrome()
	a.refreshTime = 5 * time.Second //5秒刷新一下浏览器
	return err
}

func (a *AuthTask) OnDestroy() {
	a.loginAuth.OnDestroy()
}

func (a *AuthTask) Run(closeSig chan bool) {
	ctx, cancel := context.WithCancel(context.Background())
	go func(ctx context.Context) {
		select {
		case <-ctx.Done():
			return
		default:
		A:
			err := a.loginAuth.Index(2) //过首页ip地址变动的验证码
			if err != nil {
				log.Println("过首页验证码发生错误,跳转首页")
				goto A
			} else {
				err = a.loginAuth.Login(2) //登陆
				if err != nil {
					log.Println("登陆发生错误,跳转首页")
					goto A
				} else {
					for {
						cookies, err := a.loginAuth.RefreshCookies()
						if err != nil {
							log.Println("刷新后丢失了cookie,跳转首页")
							goto A
						}
						log.Printf("%d秒刷了一次cookie\n", a.refreshTime)
						common.SetCookies(cookies)
						time.Sleep(a.refreshTime)
					}

				}
			}
		}
	}(ctx)
	for {
		select {
		case <-closeSig:
			cancel()
			return
		}
	}

}
